﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Diagnostics;
using EasySL.Server.Interface;
using System.Configuration;
using EasySL.Service;

namespace EasySL.Web
{
    public class RequestService
    {
        public RequestService()
        {
            if (ServerEnable)
                this.ConnectServer();
        }

        public bool ServerAvailable()
        {
            return (this.server != null);
        }

        private void ConnectServer()
        {
            if (this.server == null)
            {
                try
                {
                    string serviceUrl = "tcp://" + serverAddress + ":" + serverPort + "/" + serverName + ".rem";
                    this.server = (IServer)Activator.GetObject(typeof(IServer), serviceUrl);
                }
                catch (Exception)
                {
                    this.server = null;
                }
            }
        }

        public string GetData(string request)
        {
            if (ServerEnable)
            {
                if (this.server != null)
                    return this.server.GetData(request);

                throw new Exception("Server is unavalilable!");
            }
            else
            {
                return DataService.Instance.GetData(request);
            }
        }

        #region Singleton

        public static RequestService Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new RequestService();
                }

                return instance;
            }
        }

        private static RequestService instance = null;

        #endregion
      
        private static readonly string serverAddress = ConfigurationManager.AppSettings["ServerAddresss"];
        private static readonly string serverName = ConfigurationManager.AppSettings["ServerName"];
        private static readonly string serverPort = ConfigurationManager.AppSettings["ServerPort"];
        private static readonly bool ServerEnable = Boolean.Parse(ConfigurationManager.AppSettings["ServerEnable"]);

        private IServer server = null;
    }
}
